package com.example.zhaohang.bingzhuangtu;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.widget.TextView;
import android.widget.VideoView;

import com.example.zhaohang.utils.Contenct;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class FirstActivity extends BaseActivity {

    //用户安装界面的请求码
    private static final int REQUEST_INSTALL = 5;
    @InjectView(R.id.firstvideoview)
    VideoView firstvideoview;
    @InjectView(R.id.firsttext)
    TextView  firsttext;
    private int            mCount;
    private Handler        mHandler;
    private ProgressDialog mDialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        ButterKnife.inject(this);
        mHandler = new Handler();


        initData();
    }

    private void initData() {
        firstvideoview.setVideoURI(Uri.parse(Contenct.url2));
        firstvideoview.start();
        //设置一个监听，当结束时，再次重新开始
        firstvideoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                firstvideoview.start();
            }
        });


        if (true) {

            // 3.弹出提示框进行提示


            initDialog();


        } else {
            // 进入主界面
            enterHome();

        }


    }

    private void enterHome() {


        StartActivity(SecondActivity.class, true);
    }

    private void initDialog() {
        AlertDialog.Builder buidler = new AlertDialog.Builder(FirstActivity.this);
        buidler.setTitle("是否进行更新");
        buidler.setMessage(">>>1,这里修复新的bug" + "\n" + "2.添加摇一摇功能" + "\n" + "3.优化了搜索功能");
        buidler.setPositiveButton("立刻升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 5.下载apk
                DownLoadApk();


            }
        });

        buidler.setNegativeButton("取消升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                // 进入主界面
                enterHome();


            }
        });

        buidler.setCancelable(true);
        buidler.show();


    }

    private void DownLoadApk() {
        // 访问服务器，获取apk流并复制在本地SD卡
        //        InputStream inputStream = null;
        //        FileOutputStream fos = null;
        //        try {
        //            Response response = HttpUtil.HttpGet(mBean.apkUrl);

        //获取json的数据流来

        //            inputStream = response.body().byteStream();
        //            long max = response.body().contentLength();
        //            // 设置进度框的最大值
        //            progressDialog.setMax((int) max);
        //            File apkFile = new File(
        //                    Environment.getExternalStorageDirectory(),
        //                    "NetSafe17.apk");
        //            fos = new FileOutputStream(apkFile);
        //
        //            byte[] buffer = new byte[1024];
        //            int len = -1;
        //            int progress = 0;
        //
        //            while ((len = inputStream.read(buffer)) != -1) {
        //                fos.write(buffer, 0, len);
        //                progress += len;
        //                //					SystemClock.sleep(10);
        //                progressDialog.setProgress(progress);
        //            }
        //
        //            fos.flush();
        //
        //            progressDialog.dismiss();
        //            // 6.提示用户安装
        //            installApk(apkFile);
        //
        //
        //
        //        } catch (IOException e) {
        //            // 进入主界面
        //            enterHome();
        //        } finally {
        //            // closeIo(inputStream);
        //            // closeIo(fos);
        //            closeIo2(inputStream, fos);
        //        }
        //
        //    }
        //
        //    private void closeIo(Closeable io) {
        //        if (io != null) {
        //            try {
        //                io.close();
        //            } catch (IOException e) {
        //                enterHome();
        //                e.printStackTrace();
        //            }
        //        }
        //    }
        //
        //    private void closeIo2(Closeable... io) {
        //        if (io != null) {
        //            for (int i = 0; i < io.length; i++) {
        //                Closeable closeable = io[i];
        //
        //                if (closeable != null) {
        //                    try {
        //                        closeable.close();
        //                    } catch (IOException e) {
        //                        enterHome();
        //                        e.printStackTrace();
        //                    }
        //                }
        //            }
        //        }
        //
        //    }
        mDialog = new ProgressDialog(FirstActivity.this);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.show();
        mDialog.setMax(100);
        mCount = 0;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                mDialog.setProgress(mCount++);
                if (mCount >= 100) {
                    mDialog.dismiss();
                    anZhuang();
                }
                mHandler.postDelayed(this, 100);
            }
        }, 100);

    }

    private void anZhuang() {
        //	<intent-filter>
        //        <action android:name="android.intent.action.VIEW" />
        //        <category android:name="android.intent.category.DEFAULT" />
        //        <data android:scheme="content" />
        //        <data android:scheme="file" />
        //        <data android:mimeType="application/vnd.android.package-archive" />
        //    </intent-filter>

        //隐式意图安装的固定套路
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        File apkFile = new File("");
        //apk的文件名称
        Uri data = Uri.fromFile(apkFile);
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        //		startActivity(intent);

        //监听客户是否安装,并且需要复写些onActivityResult方法
        startActivityForResult(intent, REQUEST_INSTALL);
        /*
        *   // 通过Intent安装APK文件
  Intent i = new Intent(Intent.ACTION_VIEW);
  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
    "application/vnd.android.package-archive");
  mContext.startActivity(i);
  android.os.Process.killProcess(android.os.Process.myPid());
 }
如果没有android.os.Process.killProcess(android.os.Process.myPid());最后不会提示完成、打开。
如果没有i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一步的话，最后安装好了，点打开，是不会打开新版本应用的。*/


    }

    @OnClick(R.id.firsttext)
    public void onClick() {

        if (firstvideoview != null && firstvideoview.isPlaying()) {
            firstvideoview.stopPlayback();
        }

        StartActivity(SecondActivity.class, true);

        finish();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //首先确定进入安装界面
        if (requestCode == REQUEST_INSTALL) {
            switch (requestCode) {
                //确认安装
                case Activity.RESULT_OK:
                    //需要重新进入APP
                    //                    Intent intent = new Intent();
                    //                    intent.setAction("android.intent.action.youyiyi");
                    //                    startActivity(intent);


                    break;
                //取消安装
                case Activity.RESULT_CANCELED:
                    StartActivity(SecondActivity.class, true);

                    break;
            }
        }
    }
}
